/*
 * mlist.c
 *
 *  Created on: Jan 8, 2012
 *      Author: root
 */

#include "mlist.h"
/*
 * mlist -- contains all the intialized mutexes
 */
struct mlist_struct {
	uthread_mutex_t mutex;
	mlist_t next;
} mlist = {mutex : NULL, next : NULL};

int mlistAdd(uthread_mutex_t mutex) {

	mlist_t node = (struct mlist_struct*)calloc(1, sizeof(struct mlist_struct));

	if (node != NULL) {
		node->mutex = mutex;
		node->next = mlist.next;
		mlist.next = node;
		return MUTEX_SUCCESS;
	}

	return MUTEX_FAILURE;
}

mlist_t mlistSearch(uthread_mutex_t mutex) {

	if(mutex == NULL){
		return NULL;
	}

	mlist_t current = &mlist;

	while (current->next != NULL)
		if (current->next->mutex == mutex)
			return current;
		else
			current = current->next;
	return NULL;
}

int mlistDelete(uthread_mutex_t mutex) {

	if(mutex == NULL){
		return -1;
	}

	mlist_t prev = mlistSearch(mutex);

	if (prev != NULL) {
		mlist_t current = prev->next;
		prev->next = current->next;
		free(current);
		return MUTEX_SUCCESS;

	}
	else
		return MUTEX_FAILURE;
}

